package com.wolf.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign远程调用配置
 */
@Configuration
public class GuLiFeignConfig {


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //requestTemplate 是feign构造的新请求,负责调用远程接口
                //RequestContextHolder 可以拿到进入拦截器请求数据的属性信息
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //request是发起feign调用的请求
                if(requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();
                    //同步请求头信息,cookie,将发起feign调用请求的cookie信息同步给feign构造的新请求
                    requestTemplate.header("Cookie",request.getHeader("Cookie"));
                }
            }
        };
    }
}
